package com.example.springbootdoc.controller;

import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.example.springbootdoc.utils.WordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "Word文件导出")
@RestController
public class FileController {

    @ApiOperation("模板导出")
    @GetMapping("/wordDownload")
    public void word(HttpServletResponse response) throws Exception {

        response.setContentType("application/octet-stream");
        //设置文件名称
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".docx");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        InputStream inputStream = new ClassPathResource("template/addr.docx").getInputStream();


        // 创建用于插入数据的Map  实际开发要放在service层
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("title", "Hi, Word模板");
        paramMap.put("username", "小蜜蜂~");
        List<Map<String, Object>> voList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            Map<String, Object> vo = new HashMap<>();
            vo.put("areaId", String.valueOf(i));
            vo.put("name", "北京" + i);
            vo.put("phone", "1310016928" + i);
            vo.put("addr", "陕西省西安市" + i);
            vo.put("sex", "男");
            voList.add(vo);
        }


        paramMap.put("area", voList);

        // 循环行表渲染策略
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        // 插件绑定
        Configure config = Configure.builder()
                //area 变量名--policy 策略
                .bind("area", policy)
                .build();

        WordUtil.downloadWord(response.getOutputStream(), inputStream, paramMap, config);

    }
}

